package com.yunshang.shoppingmall.shopping.Weixin;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yunshang.shoppingmall.common.MessageConstants;
import com.yunshang.shoppingmall.common.Response;
import com.yunshang.shoppingmall.common.weixin.WeChat;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@Controller
@RequestMapping("/API/Weixin/")
public class TokenController {
public  static String severUrl="http://www.ycsqd.com";
    public Response getOpendId(String code, HttpServletRequest request) throws IOException {
        Logger logger= LoggerFactory.getLogger(TokenController.class);
        HttpSession session = request.getSession();
        if (code != null&&!code.equals("")) {
            //获取openid和access_token的连接
            String getOpenIdUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                    "appid="+ WeChat.appid+"" +
                    "&secret="+WeChat.appsecret+"" +
                    "&code="+code+"" +
                    "&grant_type=authorization_code";
            try {
                //获取返回的code
                String requestUrl = getOpenIdUrl.replace("CODE", code);
                CloseableHttpClient httpClient = HttpClients.createDefault();
                HttpGet httpGet = new HttpGet(requestUrl);
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                //向微信发送请求并获取response
                String response = httpClient.execute(httpGet,responseHandler);
                System.out.println("=========================获取token===================");
                System.out.println(response);
                //JsonParser parser = new JsonParser();
                JSONObject jsonObject= JSON.parseObject(response);
                //JsonObject jsonObject = (JsonObject) parser.parse(response);
                String access_token = jsonObject.get("access_token").toString();
                String openId = jsonObject.get("openid").toString();
                session.setAttribute("openid",openId);
                return new Response(MessageConstants.MSG_SYS_ERROR,1,openId);
            }catch (Exception e){
                logger.info("获取openid失败001："+e.getMessage());
                return new Response(MessageConstants.MSG_SYS_ERROR,0,"");
            }
//            System.out.println("=======================用户access_token==============");
//            System.out.println(access_token);
//            System.out.println(openId);
//            //获取用户基本信息的连接
//            String getUserInfo = "https://api.weixin.qq.com/sns/userinfo?  access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
//            String userInfoUrl = getUserInfo.replace("ACCESS_TOKEN", access_token).replace("OPENID", openId);
//            HttpGet httpGetUserInfo = new HttpGet(userInfoUrl);
//            String userInfo = httpClient.execute(httpGetUserInfo,responseHandler);
//            //微信那边采用的编码方式为ISO8859-1所以需要转化
//            String json = new String(userInfo.getBytes("ISO-8859-1"),"UTF-8");
//            System.out.println("====================userInfo==============================");
//            JSONObject jsonObject1 = JSONObject.parseObject(json);
//            String nickname = jsonObject1.get("nickname").toString();
//            String city = jsonObject1.get("city").toString();
//            String province = jsonObject1.get("province").toString();
//            String country = jsonObject1.get("country").toString();
//            String headimgurl = jsonObject1.get("headimgurl").toString();
//            //性别  1 男  2 女  0 未知
//            Integer sex = Integer.parseInt(jsonObject1.get("sex").toString());
//            System.out.println("昵称"+nickname);
//            System.out.println("城市"+city);
//            System.out.println("省"+province);
//            System.out.println("国家"+country);
//            System.out.println("头像"+headimgurl);
//            System.out.println("性别"+sex);
//            System.out.println(userInfo);
        }else {
            logger.info("获取code失败001：");
            return new Response(MessageConstants.MSG_SYS_ERROR,0,"");
        }
    }


    @RequestMapping("/code")
    @ResponseBody
    public void code(HttpServletRequest request, HttpServletResponse response,String out_trade_no) throws IOException {
        String code =   request.getParameter("code");
        System.out.println(code+"aaa");
        //code="021A8A0Y1RXL9T0V8W1Y1gYy0Y1A8A0z";
        if(code!=null&&!code.equals("")&&!code.toLowerCase().equals("null")){
           Response response1= getOpendId(code,request);
           if(response1.getData().toString().equals("1")){
               String openid=response1.getErrorDetail();
               String url=severUrl+"/API/Weixin/token?openid="+openid;
               response.sendRedirect(url);
           }else {

           }
        }else {
            System.out.println(code+"a222");
            String redirect_uri=severUrl+"/API/Weixin/code?out_trade_no="+out_trade_no+"";
            String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                    "appid="+ WeChat.appid+"" +
                    "&redirect_uri="+redirect_uri+"" +
                    "&response_type=code" +
                    "&scope=snsapi_base"+
                    "&state=STATE#wechat_redirect";
            try {
                response.sendRedirect(url);
            }catch (Exception e){
            }
        }
    }
}
